import { useConfigStore } from "./useConfigStore";

/** GA事件上报 */
export const useGA = () => {
  const isBlurTriggered = ref(false); // 当前页面是否因为点击iframe失去焦点
  const { config } = useConfigStore();

  /**
   * 自定义GA事件上报
   * @param trackEvent
   */
  const trackEvent = (trackEventValue: TrackEventType) => {
    const trackEvent = {
      ...trackEventValue,
      params: {
        ...trackEventValue.params,
        ...getTrackCommonParams(),
      },
    };
    const { eventName, params } = trackEvent;
    if (typeof window !== "undefined" && window.gtag) {
      diyConsole(`GA：${JSON.stringify(trackEvent)}`);
      window.gtag("event", eventName, params);
    }
  };

  /**
   * 自定义Tiktok事件上报
   * @param trackEvent
   */
  const trackEventTiktok = (trackEventValue: TrackEventType) => {
    const trackEvent = {
      ...trackEventValue,
      params: {
        ...trackEventValue.params,
      },
    };
    const { eventName, params } = trackEvent;
    if (typeof window !== "undefined" && window.ttq) {
      diyConsole(`Tiktok：${JSON.stringify(trackEvent)}`);
      window.ttq.track(eventName, params);
    }
  };

  /** 页面失去焦点 */
  const windowBlur = () => {
    window.addEventListener("blur", () => {
      let ACTIVELEMENT = document.activeElement;
      if (
        "IFRAME" ===
        (null === ACTIVELEMENT || undefined === ACTIVELEMENT ? undefined : ACTIVELEMENT.nodeName)
      ) {
        isBlurTriggered.value = true;
        setTimeout(() => {
          isBlurTriggered.value = false;
          window.focus(); // 延时foucs，因为广告跳转前会获取activeElement，太早focus会导致跳转前activeElement是body
        }, 300);
      }
    });
  };

  /** 监听插屏广告是否为点击关闭，_inter_close=true为关闭 */
  const windowMessage = () => {
    window._inter_close = false;
    window.addEventListener("message", (event) => {
      if (event.data && typeof event.data === "string" && event.data.includes("adClosed")) {
        diyConsole("interstitial close");
        // 这里上报插屏广告关闭
        trackEvent({
          eventName: "GAM_Inter_Close_Click",
        });
        window._inter_close = true;
      }
    });
  };

  /** 页面展示隐藏 */
  const windowVisible = () => {
    window.addEventListener("visibilitychange", () => {
      if (document.visibilityState == "hidden" && isBlurTriggered.value) {
        getTrackClick();
      } else if (document.visibilityState == "visible") {
        setTimeout(() => window.focus(), 0);
      }
    });
  };

  /** 关闭页面之前 */
  const windowBeforeUnload = () => {
    window.addEventListener("beforeunload", () => {
      const ACTIVEELEMENT = document.activeElement;
      if (
        "IFRAME" ===
        (null === ACTIVEELEMENT || undefined === ACTIVEELEMENT ? undefined : ACTIVEELEMENT.nodeName)
      ) {
        if (isInterstitialShow(ACTIVEELEMENT) && window._inter_close) {
          // 页面内跳转，非广告点击
          diyConsole("interstitial close");
        } else {
          getTrackClick();
        }
      }
    });
  };

  /** 自动插屏是否展示 */
  const isInterstitialShow = (iframe: any) => {
    let show = false;
    if (window.location.hash.indexOf("vignette") > -1) {
      let css = iframe.currentStyle || window.getComputedStyle(iframe);
      if (css.display !== "none" && iframe.clientWidth > 0 && iframe.clientHeight > 0) {
        show = true;
      }
    }
    return show;
  };

  /** 获取广告点击事件埋点 */
  const getTrackClick = () => {
    const {
      anchor,
      interstitial,
      playMRV,
      cateDetailDisplayList,
      categoryDisplayList,
      searchDisplay1,
      detailDisplay2,
      detailDisplay1,
    } = config.value?.gamConfig || {};
    /** GAM事件名称 */
    let eventName;
    /** 是否自动广告 */
    let isAutoAd = false;
    /** 谷歌渲染出来的html中的id */
    const eid = document.activeElement?.getAttribute("id");
    /** 原始GAM广告slot列表 */
    const sourceGamDefineSlot = [
      {
        gamType: GamTypeEnum.自动锚定广告,
        slot: anchor?.slot,
      },
      {
        gamType: GamTypeEnum.自动插屏广告,
        slot: interstitial,
      },
      {
        gamType: GamTypeEnum.手动激励广告,
        slot: playMRV,
      },
      {
        gamType: GamTypeEnum.手动广告,
        slot: searchDisplay1,
      },
      {
        gamType: GamTypeEnum.手动广告,
        slot: detailDisplay2,
      },
      {
        gamType: GamTypeEnum.手动广告,
        slot: detailDisplay1,
      },
      ...(cateDetailDisplayList?.map((item) => {
        return {
          gamType: GamTypeEnum.手动广告,
          slot: item,
        };
      }) || []),
      ...(categoryDisplayList?.map((item) => {
        return {
          gamType: GamTypeEnum.手动广告,
          slot: item,
        };
      }) || []),
    ]
      .flat()
      .filter(Boolean);
    /** 匹配到的原始的GAM广告slot */
    const gamDefineSlot = sourceGamDefineSlot.find((item) => eid?.includes(item.slot || ""));
    /** 普通GAM手动广告 */
    if (gamDefineSlot && gamDefineSlot.gamType === GamTypeEnum.手动广告) {
      eventName = "GAM_AD_Click";
      isAutoAd = false;
    }
    /** 自动GAM插屏广告 */
    if (gamDefineSlot && gamDefineSlot.gamType === GamTypeEnum.自动插屏广告) {
      eventName = "GAM_Inter_Click_Auto";
      isAutoAd = true;
    }
    /** 自动GAM锚定广告 */
    if (gamDefineSlot && gamDefineSlot.gamType === GamTypeEnum.自动锚定广告) {
      eventName = "GAM_Anc_Click_Auto";
      isAutoAd = true;
    }
    /** 手动激励广告 */
    if (gamDefineSlot && gamDefineSlot.gamType === GamTypeEnum.手动激励广告) {
      eventName = "GAM_MRV_Click";
      isAutoAd = false;
    }
    /** GAM广告点击的slot */
    const slot = gamDefineSlot?.slot;
    if (!slot || !eventName) return;
    trackEvent({
      eventName,
      params: { slot },
    });
    /** 收集所有GAM自动广告点击 */
    if (isAutoAd) {
      trackEvent({
        eventName: "GAM_AD_Click_Auto",
        params: { slot },
      });
    }
    /** 收集所有GAM广告的点击 */
    trackEvent({
      eventName: "GAM_AD_Click_All",
      params: { slot, eid },
    });
    /** 收集所有的adsense+GAM广告的点击 */
    trackEvent({
      eventName: "Sum_AD_Click_All",
      params: { slot },
    });
    const { network } = useRoute().query;
    /** tiktok专属上报 */
    if (network === "tiktok") {
      trackEventTiktok({ eventName: "ClickButton" });
      /** GA上报事件GAM_Inter_Click_Auto（GAM插屏广告点击）上报同时tiktok也上报 */
      if (eventName === "GAM_Inter_Click_Auto") {
        trackEventTiktok({ eventName: "AddPaymentInfo" });
        trackEventTiktok({ eventName: "AddToCart" });
      }
      /** GA上报事件GAM_Anc_Click_Auto（GAM锚定广告点击）上报同时tiktok也上报 */
      if (eventName === "GAM_Anc_Click_Auto") {
        trackEventTiktok({ eventName: "AddToWishlist" });
      }
    }
  };

  return {
    trackEvent,
    windowBlur,
    windowVisible,
    windowBeforeUnload,
    windowMessage,
  };
};
